package cn.wolfcode.luowowo.member.service.impl;

import cn.wolfcode.luowowo.api.cache.prefix.UserInfoKeyPrefix;
import cn.wolfcode.luowowo.api.cache.prefix.VerifyCodeKeyPrefix;
import cn.wolfcode.luowowo.api.cache.service.IUserInfoRedisService;
import cn.wolfcode.luowowo.api.cache.service.IVerifyCodeRedisService;
import cn.wolfcode.luowowo.common.exception.DisableException;
import cn.wolfcode.luowowo.common.util.AssertUtil;
import cn.wolfcode.luowowo.common.util.Consts;
import cn.wolfcode.luowowo.member.domain.UserInfo;
import cn.wolfcode.luowowo.member.mapper.UserInfoMapper;
import cn.wolfcode.luowowo.member.service.IUserInfoService;
import cn.wolfcode.luowowo.small.domin.Goods;
import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.StreamUtils;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.List;
import java.util.UUID;

@Service
public class UserInfoServiceImpl implements IUserInfoService {
    @Autowired
    private UserInfoMapper userInfoMapper;
    @Reference
    private IVerifyCodeRedisService verifyCodeRedisService;
    @Reference
    private IUserInfoRedisService userInfoRedisService;
    public UserInfo get(Long id) {
        return userInfoMapper.selectByPrimaryKey(id);
    }

    public boolean checkPhone(String phone) {

        return userInfoMapper.selectPhone(phone) > 0;
    }


    public void userRegist(String phone, String nickname, String password, String rpassword, String verifyCode) throws DisableException {
       //判断参数不能为空
        AssertUtil.hasLength(phone,"手机号码不能为空");
        AssertUtil.hasLength(nickname,"昵称不能为空");
        AssertUtil.hasLength(password,"密码不能为空");
        AssertUtil.hasLength(rpassword,"确认密码不能为空");
        AssertUtil.hasLength(verifyCode,"验证码不能为空");
        //判断传入的密码是否一致
        AssertUtil.isEquals(password,rpassword,"两次输入的密码不一致");
        //判断手机号码是否唯一
        if(this.checkPhone(phone)){
            throw new DisableException("手机号码已经被注册了");
        }
        //判断短信验证码是否一致
        String redisCode = verifyCodeRedisService.getVerifyCode(VerifyCodeKeyPrefix.VERIFY_CODE,phone);
        if(!redisCode.equals(verifyCode)){
            throw new DisableException("短信验证码错误");
        }
        //注册
        UserInfo userInfo = new UserInfo();
        userInfo.setPhone(phone);
        userInfo.setPassword(password);
        userInfo.setNickname(nickname);
        userInfo.setState(UserInfo.STATE_NORMAL);
        userInfo.setLevel(1);
        userInfo.setHeadImgUrl("/images/default.jpg");
        userInfoMapper.insert(userInfo);
    }

    public void sendVerifyCode(String phone) throws DisableException{
        //1.假装已经进行了手机号码校验
        String code = UUID.randomUUID().toString().substring(0, 4);
        //2.发送到用户手机
        StringBuilder content = new StringBuilder(80);
        content.append("您的短信验证码是:").append(code).append(",请在").append(Consts.VERIFY_CODE_VAI_TIME).append("分钟内输入-扣丁狼");
        System.out.println(content);
        //发送短信
        try {
            sendMsg(phone,content.toString());
        } catch (Exception e) {
            throw new DisableException("短信发送失败");
        }
        //3.缓存
        verifyCodeRedisService.setVerifyRedisCode(phone,code);


    }

    @Value("${msg.url}")
    private String msgUrl;
    @Value("${msg.appkey}")
    private String msgKey;
    @Value("${msg.uid}")
    private String msgUid;

    private void sendMsg(String phone, String content) throws DisableException, IOException {
        //Url:https://way.jd.com/chuangxin/dxjk?mobile=13568813957
        // &content=【创信】你的验证码是：5873，3分钟内有效！&appkey=148b903f94c494831d9ad3dce88da6e0

        //http://utf8.api.smschinese.cn/?Uid=本站用户名&Key=接口安全秘钥&smsMob=手机号码&smsText=验证码:8888
        //请求路径
        URL url = new URL(msgUrl);
        //建立连接
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        //设置请求方法
        connection.setRequestMethod("GET");
        //设置请求参数
        StringBuilder sb = new StringBuilder(100);
        sb.append("Uid=").append(msgUid).append("&Key=").append(msgKey).
                append("&smsMob=").append(phone).append("&smsText=").append(content);
        /*sb.append("mobile=").append(phone).append("&content=").append(content).
                append("&appkey=").append(msgKey);*/
        //设置true输出参数
        connection.setDoOutput(true);
        connection.getOutputStream().write(sb.toString().getBytes("UTF-8"));
        //请求连接
        connection.connect();
        //获取相应数据
        String resp = StreamUtils.copyToString(connection.getInputStream(), Charset.forName("UTF-8"));
        int ret = Integer.valueOf(resp);
        System.out.println(ret);
        /*if(ret <= 0 ){
            throw new DisableException("短信发送失败");
        }*/


    }

    /**
     * 登录操作
     * @param username
     * @param password
     * @return
     */
    public String userLogin(String username, String password) throws DisableException {
        UserInfo userInfo = userInfoMapper.selectUserByusernameAndPassword(username,password);
        if(userInfo == null){
            throw new DisableException("账号或密码错误");
        }
        //创建token
        return creatToken(userInfo);

    }


    public List<UserInfo> listAll() {
        return userInfoMapper.selectAll();
    }



    @Override
    public Long getCoinByUserId(Long userId) {

        return userInfoMapper.getCoinByUserId(userId);
    }

    @Override
    public void updateCoinByUserId(Long userId, Long coin) {
        userInfoMapper.updateCoinByUserId(userId,coin);
    }

    @Override
    public List<Goods> getGoodsByUserId(Long userId) {

        return  userInfoMapper.getGoodsByUserId(userId);
    }

    public void update(UserInfo userInfo) {
        userInfoMapper.updateByPrimaryKey(userInfo);
    }

    @Override
    public void addUserCoinById(Long userId,Long coin) {
        //判断如果帐户的金额为空,则插入数据
        if(userInfoMapper.getCoinByUserId(userId)==null){
            userInfoMapper.addUserCoinById(userId,coin);
        }else {
            //否则,更改数据
            Long usercoin=userInfoMapper.getCoinByUserId(userId);//先根据用户的id查出其帐户的金币
            Long newcoin=usercoin+coin;//再把用户帐户的金币与要添加的金币相加,得到用户现在更新的金币
            userInfoMapper.updateCoinByUserId(userId,userId);//更新用户的金币
        }
    }

    private String creatToken(UserInfo userInfo) {
        /**
         * 缓存登录信息
         * key:用户登录前缀+token,value:userInfo
         */
        String token = UUID.randomUUID().toString().replace("-", "");
        //添加到redis中
        userInfoRedisService.addToken(UserInfoKeyPrefix.USER_INFO_TOKEN,token,userInfo);
        return token;
    }
}
